<template>
  <div id="app">
    <h1>{{ title }}</h1>
      <ul class="todos">
        <li>
          <input type="text" placeholder="输入你要我帮你记住的事吧~" @keyup.13="addItem" v-model="newTodo">
        </li>
        <li v-for="(todo, index) in todos" :class="{'checked' : todo.done}">
          <input type="checkbox" @change="saveToStore" v-model="todo.done">
          <label>{{ index + 1 }}. {{ todo.des }}</label>
          <time>{{ todo.created | date }}</time>
          <button @click="delItem(todo)"></button>
        </li>
      </ul>
  </div>
</template>

<script>
  import "./assets/site.scss"; // 全局引入样式，每个页面都会加载
  import moment from 'moment'
  import 'moment/locale/zh-cn'

  moment.locale('zh-cn')

  export default {
    name: "app",
    data() {
      return {
        newTodo: "",
        title: "Vue-todos",
        todos: []
      };
    },

    created() {
      if(this.is_inited) {
        this.todos = JSON.parse(localStorage.getItem('VUE-TODOS'))
      }
    },

    computed: {
      is_inited(){
        return localStorage.getItem('VUE-TODOS') != null
      }
    },

    filters: {
      date(val){
        return moment(val).calendar()
      }
    },

    methods: {
      addItem() {
        this.todos.push({
          des: this.newTodo,
          created: Date.now(),
          done: false
        })
        this.saveToStore()
        this.newTodo = ''
      },
      delItem(todo) {
        // 从数组里拿出来
        this.todos = this.todos.filter((x) => x !== todo)
        this.saveToStore()
      },
      saveToStore() {
        localStorage.setItem('VUE-TODOS', JSON.stringify(this.todos))
      }
    }
  };

</script>

<style lang="scss" scoped>
  @import "./assets/todos.scss";
</style>
